
function aptReleaseInit() {
    var userHasRights = false;
    var tagList = [];
    var systemMode = {
        Null: 0,
        Prod: 1,
        NoProd: 2,
        Robot: 3,
        ICycle: 4,
      }
    emosWS.addEventListener("UserRight", function(msg) {
        // Check if users have right to release devices: 
        if (AptCheckUserRight("Release")) {
            userHasRights = true;
        } else {
            userHasRights = false;
        }
        userRightsChanged(userHasRights);
    });

    var advisedId = emosWS.getNewElementId();
    var tableSelector = "apt_ReleaseTableContainer";
    var appName = sessionStorage.getItem("apt_appName");
    var robotData;
    var languageTexts = {
        "T02_ReleaseMode": {
            id: "apt_ReleaseModeHeader",
            text: "Release mode"
        },
        "T02_ReleaseProdsHeader": {
            id: "apt_ReleaseProdModesHeader",
            text: "Prod Mode"
        },
        "T02_ReleaseNoProdModesHeader": {
            id: "apt_ReleaseNoProdModesHeader",
            text: "NoProd Mode"
        },
        "T02_ReleaseRobotModesHeader": {
            id: "apt_ReleaseRobotModesHeader",
            text: "Robot Mode"
        },
        "T02_ReleaseICycleModesHeader": {
            id: "apt_ReleaseICycleModesHeader",
            text: "ICycle Mode"
        },
        "T02_ReleaseAllDevicesHeader": {
            id: "apt_ReleaseAllDevicesHeader",
            text: "Prod Mode"
        }
    };

    $.ajax({
        url: '../../../apps/' + appName + '/global/releaseMode.JSON',
        type: 'post',
        dataType: 'json',
        async: true,
        cache: false,
        success: function(data) {
            createDom(data);
            robotData = data;
        },
        error: function(jqXHR, textStatus, errorThrown) {
            AptWriteLog("[APT Error] Could not read " + '../../../apps/' + appName + '/global/releaseMode.JSON' + ". Error: " + errorThrown + "", "error");
        }
    });

    function createDom(data) {
        var robots = Object.keys(data);
        var robotPositions = {};

        var min = [];
        var max = [];

        robots.forEach(function(robName) {
            var options = data[robName]; 
            
            var positionx = parseInt(options.X);
            var positiony = parseInt(options.Y);

            robotPositions[robName] = {
                x: positionx,
                y: positiony
            };

            if (min.length === 0) min = [positionx, positiony];
            if (max.length === 0) max = [positionx, positiony];

            if (positionx <= min[0]) min[0] = positionx;
            else if (positionx >= max[0]) max[0] = positionx;

            if (positiony <= min[1]) min[1] = positiony;
            else if (positiony >= max[1]) max[1] = positiony;
        });

        createDynamicTable(min, max, tableSelector, "robotReleaseTable", "robotReleaseTableCell");
        var handlerObj = [];

        for (var rob in data) {
            var options = data[rob];
            var x = robotPositions[rob].x;
            var y = robotPositions[rob].y;

            var html = "<div class='robReleaseWindow'>";
            html += "<table><td>" + rob + "</td>";

    
            if (options.prod.count > 0) {
              for (var i = 0; i < options.prod.count; i++) {

                // console.log(options)
                var id = getElementGlobalID();
                var overlayId = getElementGlobalID();
                var innerId = getElementGlobalID();
                html += "<td><div id='" + id + "' class='emosbutton releaseButton releaseProdMode '><div id = '" + overlayId + "' class='innerImageDiv'><div id = '" + innerId + "' class='innerImageDiv'></div></div></div><h4>" + options.prod.no[i] + "</h4></td>";


                var releaseProdModeStageTag = appName + ".IO_HmiPMR.PMR[" + options.Index + "].releaseMode.mRelease";
                var releaseProdModeTag = appName + ".IO_HmiPMR.PMR[" + options.Index + "].releaseMode.mEnable";
                var prodStateTag = appName + ".IO_HmiPMR.PMR[" + options.Index + "].releaseMode.mState";
                tagList.push(releaseProdModeTag)
                
                handlerObj.push({
                    tag: releaseProdModeStageTag,
                    id: overlayId,
                    function: function(tag, id) { handleRelease(tag, id);  }
                });
                handlerObj.push({
                    tag: releaseProdModeTag,
                    id: id,
                    function: function(tag, id) { handleToggleClick(tag, id, systemMode.Prod);  }
                });
                handlerObj.push({
                    tag: prodStateTag,
                    id: id,
                    function: function(tag, id) { handleButtonState(tag, id, systemMode.Prod); }
                });                                                            
              }   
            }

            if (options.noProd.count > 0) {
              for (var i = 0; i < options.noProd.count; i++) {
                var id = getElementGlobalID();
                var overlayId = getElementGlobalID();
                var innerId = getElementGlobalID();
                html += "<td><div id='" + id + "' class='emosbutton releaseButton releaseNoProdMode '><div id = '" + overlayId + "' class='innerImageDiv'><div id = '" + innerId + "' class='innerImageDiv'></div></div></div><h4>" + options.noProd.no[i] + "</h4></td>";

                var releaseNoProdModeStageTag = appName + ".IO_HmiPMR.PMR[" + options.Index + "].releaseMode.mRelease";
                var releaseNoProdModeTag = appName + ".IO_HmiPMR.PMR[" + options.Index + "].releaseMode.mEnable";
                var noProdStateTag = appName + ".IO_HmiPMR.PMR[" + options.Index + "].releaseMode.mState";

                handlerObj.push({
                    tag: releaseNoProdModeStageTag,
                    id: overlayId,
                    function: function(tag, id) { handleRelease(tag, id); }
                });
                handlerObj.push({
                    tag: releaseNoProdModeTag,
                    id: id,
                    function: function(tag, id) { handleToggleClick(tag, id, systemMode.NoProd); }
                });
                handlerObj.push({
                    tag: noProdStateTag,
                    id: id,
                    function: function(tag, id) { handleButtonState(tag, id, systemMode.NoProd); }
                });                                                            
              }   
            }

            if (options.robot.count > 0) {
              for (var i = 0; i < options.robot.count; i++) {
                var id = getElementGlobalID();
                var overlayId = getElementGlobalID();
                var innerId = getElementGlobalID();
                html += "<td><div id='" + id + "' class='emosbutton releaseButton releaseRobotMode '><div id = '" + overlayId + "' class='innerImageDiv'><div id = '" + innerId + "' class='innerImageDiv'></div></div></div><h4>" + options.robot.no[i] + "</h4></td>";


                // "IO_HmiPMR".PMR[1].releaseMode.Agitator[1].mRelease
                var releaseRobotModeStageTag = appName + ".IO_HmiPMR.PMR[" + options.Index + "].releaseMode.mRelease";
                var releaseRobotModeTag = appName + ".IO_HmiPMR.PMR[" + options.Index + "].releaseMode.mEnable";
                var rorbotStateTag = appName + ".IO_HmiPMR.PMR[" + options.Index + "].releaseMode.mState";

                handlerObj.push({
                    tag: releaseRobotModeStageTag,
                    id: overlayId,
                    function: function(tag, id) { handleRelease(tag, id); }
                });
                handlerObj.push({
                    tag: releaseRobotModeTag,
                    id: id,
                    function: function(tag, id) { handleToggleClick(tag, id, systemMode.Robot); }
                });
                handlerObj.push({
                    tag: rorbotStateTag,
                    id: id,
                    function: function(tag, id) { handleButtonState(tag, id, systemMode.Robot); }
                });                                                            
              }   
            }

            if (options.iCycle.count > 0) {
                for (var i = 0; i < options.iCycle.count; i++) {
                  var id = getElementGlobalID();
                  var overlayId = getElementGlobalID();
                  var innerId = getElementGlobalID();
                  html += "<td><div id='" + id + "' class='emosbutton releaseButton releaseICycleMode '><div id = '" + overlayId + "' class='innerImageDiv'><div id = '" + innerId + "' class='innerImageDiv'></div></div></div><h4>" + options.iCycle.no[i] + "</h4></td>";
  

                  // "IO_HmiPMR".PMR[1].releaseMode.Agitator[1].mRelease
                  var releaseICycleModeStageTag = appName + ".IO_HmiPMR.PMR[" + options.Index + "].releaseMode.mRelease";
                  var releaseICycleModeTag = appName + ".IO_HmiPMR.PMR[" + options.Index + "].releaseMode.mEnable";
                  var iCycletateTag = appName + ".IO_HmiPMR.PMR[" + options.Index + "].releaseMode.mState";
  
                  handlerObj.push({
                      tag: releaseICycleModeStageTag,
                      id: overlayId,
                      function: function(tag, id) { handleRelease(tag, id); }
                  });
                  handlerObj.push({
                      tag: releaseICycleModeTag,
                      id: id,
                      function: function(tag, id) { handleToggleClick(tag, id, systemMode.ICycle); }
                  });
                  handlerObj.push({
                      tag: iCycletateTag,
                      id: id,
                      function: function(tag, id) { handleButtonState(tag, id, systemMode.ICycle); }
                  });                                                            
                }   
              }


            html += "</table></div>";
            placeHtmlInTable(html, x, y, tableSelector);
        }

        // Execute all functions for all buttons
        handlerObj.forEach(function(obj) {
            obj.function(obj.tag, obj.id);
        });

    }

    function handleRelease(tag, id) {
        emosWS.advise(tag, function(msg) {
            if (parseInt(msg.value) === 0) {
                $('#' + id).addClass("unreleased");
            } else {
                $('#' + id).removeClass("unreleased");
            }
        }).setId(advisedId);
    }

    function handleToggleClick(tag, id,value) {
        $('#' + id).click(function() {
            emosWS.poke(tag, value);
            console.log(tag) 
        });
    }

    function handleButtonState(tag, id, target) {
        emosWS.advise(tag, function(msg) {
            var element = $('#' + id);
            if(msg.value == null) {
                handleButtonStateCss(element, "red");
                return;
            }
            if(parseInt(msg.value) == target){
                handleButtonStateCss(element, "green");
            }else{
                handleButtonStateCss(element, "grey");
            }
        }).setId(advisedId);
    }

    function handleButtonStateCss(element, addedColor) {
        var cssClasses = $(element).attr('class').split(/\s+/)
        for (var i = 0; i < cssClasses.length; i++) {
            if (cssClasses[i].startsWith("state")) {
                element.removeClass(cssClasses[i]);
            }
        }
        element.addClass("state" + addedColor);
    }

    function releaseAll(value) {
        tagList.forEach(e => {
            emosWS.poke(e, value);
        });  
    }


    function userRightsChanged() {
        // if (userHasRights) {
        //     $('.emosbutton').removeClass("disabled");
        // } else {
        //     $('.emosbutton').addClass("disabled");
        // }
    }

    function eventHandler() {
        $('#apt_ReleaseContainer').on("remove", function() {
            emosWS.unadvise(advisedId);
        });

        $('#racProdModeOnButton').click(function() {
            releaseAll(systemMode.Prod);
        });

        $('#racProdModeOffButton').click(function() {
            releaseAll(systemMode.Null)
        });

        $('#racNoProdOnButton').click(function() {
            releaseAll(systemMode.NoProd)
        });

        $('#racNoProdOffButton').click(function() {
            releaseAll(systemMode.Null)
        });

        $('#racRobotOnButton').click(function() {
            releaseAll(systemMode.Robot)
        });

        $('#racRobotOffButton').click(function() {
            releaseAll(systemMode.Null)
        });
        $('#racICycleOnButton').click(function() {
            releaseAll(systemMode.ICycle)
        });

        $('#racICycleOffButton').click(function() {
            releaseAll(systemMode.Null)
        });
        $('#toDevicesOnButton').click(function() {
            releaseAll(systemMode.Prod)
        });

        $('#toDevicesOffButton').click(function() {
            releaseAll(systemMode.Null)
        });

        // $('body').click(function() {
        //     if (!userHasRights) {
        //         if ($('#login').length === 0) $('#login', parent.document).trigger('click');
        //         else $('#login').trigger('click');
        //     }
        // });
    }

    languageHandler(languageTexts);
    eventHandler();
}


function initReleaseWindow() {
    emosWS.connect({ onopen: aptReleaseInit() });
}